package com.fingard.dsp.bank.directbank.ceb02.bankUtil;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.KeyStore;

import javax.net.ssl.SSLSession;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;

import com.fingard.dsp.bank.directbank.DirectBase;
import com.sun.net.ssl.KeyManagerFactory;
import com.sun.net.ssl.SSLContext;
import com.sun.net.ssl.TrustManagerFactory;

public class HttpHelper extends DirectBase {

    private final static String charset = "GB18030";

    /**
              * 客户端证书设置
     */
    protected String clientCertPwd = "CA789789";// 客户端证书密码
    protected String clientCertPath = "D:\\DSPCEB02\\config\\portfiles\\CEB02\\CAGDGYL.pfx";
    protected String clientKeyType = "pkcs12";
    /**
              * 服务端证书设置
     */
    protected String truestCertPwd = "CA789789";
    protected String  trustCertPath ="D:\\DSPCEB02\\config\\portfiles\\CEB02\\CAGDGYL.pfx";
    protected String truestKeyType = "pfx";

    private SSLContext sslContext;

    /**
     * post方法
     */
    public  String[] post(byte[] request, String requestAddr) throws IOException{
    	String[] retStr = new String[]{"",""};
        StringBuffer sb = null;
        HttpsURLConnection urlCon = null;

        OutputStream os = null;
        InputStream fis = null;
        BufferedInputStream bis = null;

        InputStream is = null;
        BufferedReader br = null;
        try {
            if (sslContext == null) {
                sslContext = SSLContext.getInstance("TLSv1");
                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
                TrustManagerFactory tmf = TrustManagerFactory
                        .getInstance("SunX509");

                KeyStore keyStore = KeyStore.getInstance(clientKeyType);
                keyStore.load(new FileInputStream(clientCertPath),
                        clientCertPwd.toCharArray());
                kmf.init(keyStore, clientCertPwd.toCharArray());

                KeyStore trustKeyStore = KeyStore.getInstance(truestKeyType);
                trustKeyStore.load(new FileInputStream(trustCertPath),
                        truestCertPwd.toCharArray());
                tmf.init(trustKeyStore);
                sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
                HostnameVerifier hv = new HostnameVerifier() {
					public boolean verify(String urlHostName, SSLSession session) {
						return true;
					}

				};
				HttpsURLConnection.setDefaultHostnameVerifier(hv);
            }

            URL url = new URL(null,requestAddr, new sun.net.www.protocol.https.Handler());
            if (url.getProtocol().toLowerCase().equals("https")) {

            	urlCon =  (HttpsURLConnection) url.openConnection(); 

            	}
           // urlCon.setConnectTimeout(65000);
          //  urlCon.setReadTimeout(55000);
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setRequestMethod("POST");
            //urlCon.setRequestProperty("Content-type", "application/json");
            urlCon.setRequestProperty("Content-type", "text/plain");
            urlCon.setRequestProperty("charset", charset);
            urlCon.setSSLSocketFactory(sslContext.getSocketFactory());

            os = urlCon.getOutputStream();
            fis = new ByteArrayInputStream(request);
            bis = new BufferedInputStream(fis);
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = bis.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
            closeOutputStream(os, fis, bis);

            is = urlCon.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "GBK"));
            sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            retStr[1] = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                closeOutputStream(os, fis, bis);
                closeInputStream(is, br);
                closeUrlCon(urlCon);
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return retStr;
    }

    /**
     * @param urlCon
     */
    private static void closeUrlCon(HttpsURLConnection urlCon) {
        if (urlCon != null) {
            urlCon.disconnect();
        }
    }

    /**
     * @param is
     * @param br
     * @throws IOException
     */
    private static void closeInputStream(InputStream is, BufferedReader br)
            throws IOException {
        if (br != null) {
            br.close();
        }
        if (is != null) {
            is.close();
        }
    }

    /**
     * @param os
     * @param fis
     * @param bis
     * @throws IOException
     */
    private static void closeOutputStream(OutputStream os, InputStream fis,
                                          BufferedInputStream bis) throws IOException {
        if (os != null) {
            os.flush();
        }
        if (bis != null) {
            bis.close();
        }
        if (fis != null) {
            fis.close();
        }
        if (os != null) {
            os.close();
        }
    }

    public String getTruestCertPwd() {
        return truestCertPwd;
    }

    public void setTruestCertPwd(String truestCertPwd) {
        this.truestCertPwd = truestCertPwd;
    }

    public String getClientCertPwd() {
        return clientCertPwd;
    }

    public void setClientCertPwd(String clientCertPwd) {
        this.clientCertPwd = clientCertPwd;
    }

    public String getClientCertPath() {
        return clientCertPath;
    }

    public void setClientCertPath(String clientCertPath) {
        this.clientCertPath = clientCertPath;
    }

    public String getTrustCertPath() {
        return trustCertPath;
    }

    public void setTrustCertPath(String trustCertPath) {
        this.trustCertPath = trustCertPath;
    }

    public String getTruestKeyType() {
        return truestKeyType;
    }

    public void setTruestKeyType(String truestKeyType) {
        this.truestKeyType = truestKeyType;
    }

    public String getClientKeyType() {
        return clientKeyType;
    }

    public void setClientKeyType(String clientKeyType) {
        this.clientKeyType = clientKeyType;
    }
}
